package net.linku.aspect;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.linku.model.WebLog;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.core.annotation.Order;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * AOP切面类，用于记录Web请求日志
 */
@Aspect
@Component
@Order(1)
@Slf4j
public class WebLogAspect {

    /**
     * 定义切入点，匹配net.linku.controller包及其子包下的所有方法
     */
    @Pointcut("execution(* net.linku.controller.*.*(..))")
    public void webLog() {
    }

    /**
     * 环绕通知，记录Web请求日志
     *
     * @param proceedingJoinPoint 连接点
     * @return 方法执行结果
     * @throws Throwable 抛出异常
     */
    @Around("webLog()")
    public Object recordWebLog(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        WebLog webLog = new WebLog();

        // 获取当前请求对象
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        // 检查当前请求是否处于异步模式
        if (request.isAsyncStarted()) {
            log.info("The request is in asynchronous mode.");
        }

        // 执行目标方法
        Object result = proceedingJoinPoint.proceed();

        long end = System.currentTimeMillis();

        // 设置WebLog属性
        MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
        Method method = signature.getMethod();
        String targetClassName = proceedingJoinPoint.getTarget().getClass().getName();
        ApiOperation annotation = method.getAnnotation(ApiOperation.class);

        webLog.setSpendTime((int) (end - start) / 1000);
        webLog.setUri(request.getRequestURI());
        webLog.setUrl(request.getRequestURL().toString());
        webLog.setBasePath(StrUtil.removeSuffix(request.getRequestURL().toString(), URLUtil.url(request.getRequestURL().toString()).getPath()));
        webLog.setUsername(getUsername());
        webLog.setIp(request.getRemoteAddr());
        webLog.setDescription(annotation == null ? "no desc" : annotation.value());
        webLog.setMethod(targetClassName + "." + method.getName());
        webLog.setParameter(getMethodParameters(method, proceedingJoinPoint.getArgs()));
        webLog.setResult(result);

        // 记录日志
        log.info(JSON.toJSONString(webLog, SerializerFeature.IgnoreErrorGetter));

        return result;
    }

    /**
     * 获取当前用户名
     *
     * @return 用户名
     */
    private String getUsername() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication == null ? "anonymous" : authentication.getPrincipal().toString();
    }

    /**
     * 获取方法参数名称和值的映射
     *
     * @param method 方法对象
     * @param args 方法参数值
     * @return 方法参数名称和值的映射
     */
    private Map<String, Object> getMethodParameters(Method method, Object[] args) {
        Map<String, Object> methodParametersWithValues = new HashMap<>();
        String[] parameterNames = new LocalVariableTableParameterNameDiscoverer().getParameterNames(method);
        for (int i = 0; i < parameterNames.length; i++) {
            // 对敏感信息进行处理
            if ("password".equals(parameterNames[i]) || "file".equals(parameterNames[i])) {
                methodParametersWithValues.put(parameterNames[i], "受限的支持类型");
            } else {
                methodParametersWithValues.put(parameterNames[i], args[i]);
            }
        }
        return methodParametersWithValues;
    }
}
